<?php
// $Id$

/**
 * Smslog 封装来自 sms_log 数据表的记录及领域逻辑
 */
class fxcommission extends QDB_ActiveRecord_Abstract
{

    /**
     * 返回对象的定义
     *
     * @static
     *
     * @return array
     */
    static function __define()
    {
        return array
        (
            // 指定该 ActiveRecord 要使用的行为插件
            'behaviors' => '',

            // 指定行为插件的配置
            'behaviors_settings' => array
            (
                # '插件名' => array('选项' => 设置),
            ),

            // 用什么数据表保存对象
            'table_name' => 'edu_fx_commission',

            // 指定数据表记录字段与对象属性之间的映射关系
            // 没有在此处指定的属性，QeePHP 会自动设置将属性映射为对象的可读写属性
            'props' => array
            (
                // 主键应该是只读，确保领域对象的“不变量”
                'id' => array('readonly' => true),

                // 对象创建时间应该是只读
                'addtime' => array('readonly' => true),


                /**
                 *  可以在此添加其他属性的设置
                 */
                # 'other_prop' => array('readonly' => true),

                /**
                 * 添加对象间的关联
                 */
                # 'other' => array('has_one' => 'Class'),
//         	'agent'=>array('has_one'=>'acct','source_key'=>'agent_id','target_id'=>'id'),
//             'admin'=>array('has_one'=>'acct','source_key'=>'admin_id','target_id'=>'id')

            ),

            /**
             * 允许使用 mass-assignment 方式赋值的属性
             *
             * 如果指定了 attr_accessible，则忽略 attr_protected 的设置。
             */
            'attr_accessible' => '',

            /**
             * 拒绝使用 mass-assignment 方式赋值的属性
             */
            'attr_protected' => 'id',

            /**
             * 指定在数据库中创建对象时，哪些属性的值不允许由外部提供
             *
             * 这里指定的属性会在创建记录时被过滤掉，从而让数据库自行填充值。
             */
            'create_reject' => '',

            /**
             * 指定更新数据库中的对象时，哪些属性的值不允许由外部提供
             */
            'update_reject' => '',

            /**
             * 指定在数据库中创建对象时，哪些属性的值由下面指定的内容进行覆盖
             *
             * 如果填充值为 self::AUTOFILL_TIMESTAMP 或 self::AUTOFILL_DATETIME，
             * 则会根据属性的类型来自动填充当前时间（整数或字符串）。
             *
             * 如果填充值为一个数组，则假定为 callback 方法。
             */
            'create_autofill' => array
            (
                # 属性名 => 填充值
                # 'is_locked' => 0,
               
               'addtime' => self::AUTOFILL_TIMESTAMP 
            ),

            /**
             * 指定更新数据库中的对象时，哪些属性的值由下面指定的内容进行覆盖
             *
             * 填充值的指定规则同 create_autofill
             */
            'update_autofill' => array
            (
            ),

            /**
             * 在保存对象时，会按照下面指定的验证规则进行验证。验证失败会抛出异常。
             *
             * 除了在保存时自动验证，还可以通过对象的 ::meta()->validate() 方法对数组数据进行验证。
             *
             * 如果需要添加一个自定义验证，应该写成
             *
             * 'title' => array(
             *        array(array(__CLASS__, 'checkTitle'), '标题不能为空'),
             * )
             *
             * 然后在该类中添加 checkTitle() 方法。函数原型如下：
             *
             * static function checkTitle($title)
             *
             * 该方法返回 true 表示通过验证。
             */
            'validations' => array
            (
                
            ),
        );
    }


/* ------------------ 以下是自动生成的代码，不能修改 ------------------ */

    /**
     * 开启一个查询，查找符合条件的对象或对象集合
     *
     * @static
     *
     * @return QDB_Select
     */
    static function find()
    {
        $args = func_get_args();
        return QDB_ActiveRecord_Meta::instance(__CLASS__)->findByArgs($args);
    }

    /**
     * 返回当前 ActiveRecord 类的元数据对象
     *
     * @static
     *
     * @return QDB_ActiveRecord_Meta
     */
    static function meta()
    {
        return QDB_ActiveRecord_Meta::instance(__CLASS__);
    }


/* ------------------ 以上是自动生成的代码，不能修改 ------------------ */
    //获取提成佣金列表
    static function getlist($user_id,$page=1,$limit = 10){
        $cp = ($page-1)*$limit;
        $sql = "select c.*,u.nickname,u.avatar_url from edu_fx_commission as c left join acct_user as u on c.user_id = u.id where c.object_uid = $user_id order by addtime desc limit $cp,$limit";
        $list = QDB::getConn()->execute($sql)->fetchAll();
        return Helper_common::autoFormatTime($list);
    }

    //添加佣金计算及添加收入

    static function addcommission($order_id){
        $order_info = coreorder::find("id = ".$order_id)->getOne();
        $user_id = $order_info->user_id;
        $user_info = acctuser::find("id = ?",$user_id)->getOne();
        $acct_id = $order_info->acct_id;
        $total_consume = $user_info->total_consume;
        //检查分销等级及升级
        $sql = "select * from edu_fx_level_set where acct_id = $acct_id and upgrade_condition <= $total_consume order by upgrade_condition desc limit 1";
        $list = QDB::getConn()->execute($sql)->fetchAll();
        if(!empty($list[0])){
            if($user_info->fx_grade != $list[0]['grade']){
                $user_info->fx_grade = $list[0]['grade'];
                $user_info->save();
            }
        }
        //判断分销开关
        $fxset = fxset::find(array("acct_id"=>$order_info->acct_id,"is_open"=>1))->getOne();
        if(empty($fxset->id)){
            return false;
        }
        

        //判断是否已经计算过提成
        $comm = fxcommission::find(array("order_sn"=>$order_info->ordersn))->getCount();
        if($comm>0){
            return false;
        }
        
        
        //判断订单是否为打赏
        if($order_info->module_mark == 'reward' || $order_info->module_mark == 'activity' ){
            return false;
        }
        //分销订单类型
        switch ($order_info->module_mark) {
            case 'video':
                $fx_type = 0;
                $fx_type_name = "视频/直播";
                break;
            case 'shop':
                $fx_type = 1;
                $fx_type_name = "商品";
                break;
            case 'vip':
                $fx_type = 2;
                $fx_type_name = "充值VIP";
                break;
            case 'paper':
                $fx_type = 3;
                $fx_type_name = "题库";
                break;
        }
        //获取父级信息
        $parentids = acctuser::getmyparentids($user_id);
        
        if($parentids==false){
            //没有父级
            return false;
        }else{
            //有父级
            $cids = array_reverse($parentids);
            if(!empty($cids[0]) && $fxset->level>0){
                $fuser = acctuser::find("id = ".$cids[0])->getOne();
                $consume = $fuser->total_consume;
                //检查更新父级分销商级别
                $sql = "select * from edu_fx_level_set where acct_id = $acct_id and upgrade_condition <= $consume order by upgrade_condition desc limit 1";
                $list = QDB::getConn()->execute($sql)->fetchAll();
                if(!empty($list[0])){
                    if($fuser->fx_grade != $list[0]['grade']){
                        $fuser->fx_grade = $list[0]['grade'];
                        $fuser->save();
                    }
                }
                //第一级提成
                
                $is_vip = $fuser->viplevel_id==0 || $fuser->due_time<time()?0:1;
                
                //分销商比例获取
                $fxlevelset = fxlevelset::find(array("acct_id"=>$acct_id,"type"=>$fx_type,"grade"=>$fuser->fx_grade))->getOne();
                //提成金额
                $pirce = floatval($fxlevelset->level1_rate)*floatval($order_info->fee)/100;
                $data = array(
                    "type" => $fx_type,
                    "user_id" =>$user_id,
                    "order_sn"=>$order_info->ordersn,
                    "object_uid" => $cids[0],
                    "acct_id" => $acct_id,
                    "level" => 1,
                    "money" => $pirce,
                    "msg" => $user_info->nickname."购买".$fx_type_name
                );
                $commission = new fxcommission($data);
                $commission->save();
                fxcommission::addusercommission($commission,$fuser);
            }

            if(!empty($cids[1]) && $fxset->level>1){
                //第二级提成
                $fuser = acctuser::find("id = ".$cids[1])->getOne();
                $consume = $fuser->total_consume;
                //检查更新父级分销商级别
                $sql = "select * from edu_fx_level_set where acct_id = $acct_id and upgrade_condition <= $consume order by upgrade_condition desc limit 1";
                $list = QDB::getConn()->execute($sql)->fetchAll();
                if(!empty($list[0])){
                    if($fuser->fx_grade != $list[0]['grade']){
                        $fuser->fx_grade = $list[0]['grade'];
                        $fuser->save();
                    }
                }
                $is_vip = $fuser->viplevel_id==0 || $fuser->due_time<time()?0:1;

                //分销商比例获取
                $fxlevelset = fxlevelset::find(array("acct_id"=>$acct_id,"type"=>$fx_type,"grade"=>$fuser->fx_grade))->getOne();
                //提成金额
                $pirce = floatval($fxlevelset->level2_rate)*floatval($order_info->fee)/100;
                $data = array(
                    "type" => $fx_type,
                    "user_id" =>$user_id,
                    "order_sn"=>$order_info->ordersn,
                    "object_uid" => $cids[1],
                    "acct_id" => $acct_id,
                    "level" => 2,
                    "money" => $pirce,
                    "msg" => $user_info->nickname."购买".$fx_type_name
                );
                $commission = new fxcommission($data);
                $commission->save();
                fxcommission::addusercommission($commission,$fuser);

            }

            //第三级提成
            if(!empty($cids[2]) && $fxset->level>2){
                $fuser = acctuser::find("id = ?",$cids[2])->getOne();
                $consume = $fuser->total_consume;
                //检查更新父级分销商级别
                $sql = "select * from edu_fx_level_set where acct_id = $acct_id and upgrade_condition <= $consume order by upgrade_condition desc limit 1";
                $list = QDB::getConn()->execute($sql)->fetchAll();
                if(!empty($list[0])){
                    if($fuser->fx_grade != $list[0]['grade']){
                        $fuser->fx_grade = $list[0]['grade'];
                        $fuser->save();
                    }
                }
                $is_vip = $fuser->viplevel_id==0 || $fuser->due_time<time()?0:1;
                $fxset = fxset::find(array("acct_id"=>$acct_id,"level"=>3,"fx_man"=>$is_vip,"is_open"=>1))->getOne();
                //分销商比例获取
                $fxlevelset = fxlevelset::find(array("acct_id"=>$acct_id,"type"=>$fx_type,"grade"=>$fuser->fx_grade))->getOne();
                //提成金额
                $pirce = floatval($fxlevelset->level3_rate)*floatval($order_info->fee)/100;
                $data = array(
                    "type" => $fx_type,
                    "user_id" =>$user_id,
                    "order_sn"=>$order_info->ordersn,
                    "object_uid" => $cids[2],
                    "acct_id" => $acct_id,
                    "level" => 3,
                    "money" => $pirce,
                    "msg" => $user_info->nickname."购买".$fx_type_name
                );
                $commission = new fxcommission($data);
                $commission->save();
                fxcommission::addusercommission($commission,$fuser);
            }
            return true;
        }


    }
    //添加佣金结算
    static function addusercommission($comm,$user){
        //分销商升级
        $wait_commission=0;
        $commission = 0;
        if($comm->type==1){
            $order = shoporder::find(array("ordersn"=>$comm->order_sn))->setColumns('id,status')->getOne();
            if($order->status==99){
                //订单已完成
                $commission = $comm->money;
            }
            if($order->status==3||$order->status==4){
                //订单进行中
                $wait_commission = $comm->money;
            }

        }else{
            $commission = $comm->money;
        }
        $user->wait_commission = $user->wait_commission+$wait_commission;
        $user->commission = $user->commission+$commission;
        $user->save();
    }

    //更新佣金
    static function updateusercommission($uid){
        $comm = fxcommission::find(array("object_uid"=>$uid))->getAll();
        $commission = 0;
        $wait_commission = 0;
        foreach ($comm as $value) {
            if($value->type==1){
                $order = shoporder::find(array("ordersn"=>$value->order_sn))->setColumns('id,status')->getOne();
                if($order->status==99){
                    //订单已完成
                    $commission+=$value->money;
                }
                if($order->status==3||$order->status==4){
                    //订单进行中
                    $wait_commission+=$value->money;
                }

            }else{
                $commission+=$value->money;
            }
        }
        $user = acctuser::find("id = ".$uid)->getOne();
        $user->wait_commission = $wait_commission;
        $user->commission = $commission - $user->used_commission;
        $user->save();
    }


}

